<template>
  <Card
    :title="title"
    :bordered="false"
    :head-style="{ padding: '0' }"
    :body-style="{ padding: '10px 0' }"
    v-loading="loading"
  >
    <template #extra>
      <div class="flex gap-2 items-center">
        <Alert
          message="邮件更新中"
          type="info"
          style="padding: 4px 15px"
          show-icon
          v-if="isShowAlert"
        >
          <template #icon><sync-outlined spin /></template>
        </Alert>
        <Select
          :options="emailList"
          v-model:value="emailInfo.id"
          style="width: 200px"
          @change="handleChangeEmail"
        />
      </div>
    </template>
    <div style="background-color: #e7eff6" class="flex justify-start gap-2 p-8px">
      <Dropdown :trigger="['hover']" :overlayStyle="{ width: '78px', minWidth: '78px' }">
        <Button type="primary">
          <template #icon>
            <DownOutlined />
          </template>
          选择
        </Button>
        <template #overlay>
          <Menu>
            <MenuItem @click.stop="handleSelect('全选')"> 全选 </MenuItem>
            <MenuItem @click.stop="handleSelect('不选')"> 不选 </MenuItem>
            <MenuItem @click.stop="handleSelect('未读')"> 未读 </MenuItem>
            <MenuItem @click.stop="handleSelect('已读')"> 已读 </MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <Button type="primary" @click="handleRefresh">
        <template #icon>
          <RedoOutlined />
        </template>
        刷新
      </Button>
      <Button @click="handleDeleteBatch">
        <template #icon> <DeleteOutlined style="color: red" /> </template>
        删除
      </Button>
      <Button type="primary" @click="handleTransmit">
        <template #icon>
          <SendOutlined />
        </template>
        转发
      </Button>
      <Dropdown :trigger="['hover']" :overlayStyle="{ width: '96px', minWidth: '106px' }">
        <Button type="primary">
          <template #icon>
            <ReadOutlined />
          </template>
          置为已读
        </Button>
        <template #overlay>
          <Menu>
            <MenuItem @click.stop="handleRead('1')"> 已读 </MenuItem>
            <MenuItem @click.stop="handleRead('0')"> 未读 </MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <Dropdown :trigger="['hover']" :overlayStyle="{ width: '96px', minWidth: '96px' }">
        <Button type="primary">
          <template #icon>
            <SwapOutlined />
          </template>
          移动到
        </Button>
        <template #overlay>
          <Menu>
            <MenuItem @click.stop="handleMoveData(3)"> 发件箱 </MenuItem>
            <MenuItem @click.stop="handleMoveData(0)"> 草稿箱 </MenuItem>
            <MenuItem @click.stop="handleMoveData(2)"> 删除 </MenuItem>
          </Menu>
        </template>
      </Dropdown>
    </div>
    <BasicTable @register="registerTable" class="custom-table">
      <!-- <template #toolbar> </template> -->
      <template #sender="{ text, record }">
        <a-button
          type="link"
          @click="handleView(record)"
          :style="{ fontWeight: record.isReaded ? '' : 'bold' }"
        >
          {{ text }}
        </a-button>
      </template>
      <template #subject="{ text, record }">
        <a-button type="link" @click="handleView(record)">
          {{ text }}
        </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:info-standard-line',
              onClick: handleView.bind(null, record),
              tooltip: '查看',
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              popConfirm: {
                title: '是否确认删除',
                placement: 'leftBottom',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
  </Card>
</template>
<script lang="ts">
  import { defineComponent, h, ref, onMounted, inject, computed, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { columns, searchFormSchema } from './inbox.data';
  import {
    getEmailListInbox,
    getEmailFetchMail,
    getEmailSetReaded,
    getEmailDelMail,
    getEmailMoveMail,
  } from '/@/api/email/externalEmail';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useGo } from '/@/hooks/web/usePage';
  import { useModal } from '/@/components/Modal';
  import { Card, Input, Select, Button, Dropdown, Menu, Alert } from 'ant-design-vue';
  import {
    RedoOutlined,
    DeleteOutlined,
    SendOutlined,
    ReadOutlined,
    SwapOutlined,
    SyncOutlined,
    DownOutlined,
  } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { getEmailListEmail } from '/@/api/email/externalEmail';
  export default defineComponent({
    name: 'InboxList',
    components: {
      BasicTable,
      TableAction,
      Card,
      Input,
      Select,
      Button,
      RedoOutlined,
      DeleteOutlined,
      SendOutlined,
      ReadOutlined,
      Dropdown,
      Menu,
      MenuItem: Menu.Item,
      SwapOutlined,
      Alert,
      SyncOutlined,
      DownOutlined,
    },
    emits: ['handle-transmit', 'handle-view'],
    setup(_, { emit }) {
      const go = useGo();
      const loading = ref(false);
      const { createMessage, createConfirm } = useMessage();
      const userStore = useUserStore();
      const userInfo = userStore.getUserInfo || {};
      const internalEmail = inject('internalEmail') as any;
      const emailInfo = ref<Recordable>({});
      watch(
        () => internalEmail.emailInfo.value,
        (newVal) => {
          if (newVal) {
            emailInfo.value = newVal;
          }
        },
        {
          immediate: true,
        },
      );
      const emailList = ref<Recordable[]>([]);
      const [
        registerTable,
        { reload, getSelectRowKeys, getSelectRows, getDataSource, setSelectedRowKeys },
      ] = useTable({
        title: '',
        api: getEmailListInbox,
        columns,
        formConfig: {
          labelWidth: 0,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
          actionColOptions: {
            sm: 8,
            md: 8,
            lg: 6,
            xl: 5,
            xxl: 3,
          },
        },
        searchInfo: {
          action: 'search',
        }, //额外的参数
        beforeFetch: (info) => {
          if (internalEmail.emailInfo.value.id != -1) {
            info.emailId = internalEmail.emailInfo.value.id;
          }
          return info;
        },
        rowSelection: {
          type: 'checkbox',
          columnWidth: 40,
        },
        clickToRowSelect: false,
        useSearchForm: true,
        showTableSetting: false,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        rowKey: 'id',
        canResize: false,
        immediate: false,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: undefined,
        },
      });

      const title = computed(() => `收件箱(${emailInfo.value.email})`);

      async function handleDelete(record: Recordable) {
        try {
          loading.value = true;
          await getEmailDelMail({ emailId: internalEmail.emailInfo.value.id, ids: record.id });
          handleSuccess();
        } catch (error) {
          console.log(error);
        } finally {
          loading.value = false;
        }
      }

      async function handleDeleteBatch() {
        let checkes = getSelectRowKeys();
        if (checkes.length == 0) {
          createMessage.warn('删除数据不能为空');
          return;
        }

        createConfirm({
          iconType: 'warning',
          title: () => h('span', '您确定删除么？'),
          onOk: async () => {
            let ids = checkes.join(',');
            try {
              loading.value = true;
              await getEmailDelMail({ emailId: internalEmail.emailInfo.value.id, ids: ids });
              handleSuccess();
            } catch (error) {
              console.log(error);
            } finally {
              loading.value = false;
            }
          },
        });
      }

      function handleSuccess() {
        reload();
      }

      function handleView(record: Recordable) {
        emit('handle-view', record);
      }

      //刷新
      const handleRefresh = () => {
        setSelectedRowKeys([]);
        reload();
      };

      //转发
      const handleTransmit = () => {
        const rews = getSelectRows();
        if (rews.length == 0) {
          createMessage.warn('请选择数据');
          return;
        }
        emit('handle-transmit', rews[0]);
      };

      //置为已读
      const handleRead = async (val) => {
        let checkes = getSelectRowKeys();
        if (checkes.length == 0) {
          createMessage.warn('请选择数据');
          return;
        }
        const moduleCodes = checkes.join(',');
        try {
          loading.value = true;
          await getEmailSetReaded({
            emailId: internalEmail.emailInfo.value.id,
            ids: moduleCodes,
            isReaded: val,
          });
          createMessage.success('操作成功');
          handleRefresh();
        } finally {
          loading.value = false;
        }
      };

      //移动到
      const handleMoveData = async (type) => {
        let checkes = getSelectRowKeys();
        if (checkes.length == 0) {
          createMessage.warn('请选择数据');
          return;
        }
        try {
          const params = {
            emailId: internalEmail.emailInfo.value.id,
            // sender: '',
            ids: checkes.join(','),
            box: type,
          };
          loading.value = true;
          await getEmailMoveMail(params);
          loading.value = false;
          handleRefresh();
        } catch (error) {
          loading.value = false;
        }
      };

      //选择
      const handleSelect = (type) => {
        switch (type) {
          case '全选':
            const data1 = getDataSource();
            const keys1 = data1.map((item) => item.id);
            setSelectedRowKeys(keys1);
            break;
          case '不选':
            setSelectedRowKeys([]);
            break;
          case '未读':
            const data2 = getDataSource();
            const keys2 = data2.filter((item) => !item.isReaded).map((el) => el.id);
            setSelectedRowKeys(keys2);
            break;
          case '已读':
            const data3 = getDataSource();
            const keys3 = data3.filter((item) => !!item.isReaded).map((el) => el.id);
            setSelectedRowKeys(keys3);
            break;
        }
      };

      //更新邮件
      const isShowAlert = ref(false);
      const getEmailFetchMailData = async () => {
        try {
          isShowAlert.value = true;
          const data = await getEmailFetchMail({ emailId: internalEmail.emailInfo.value.id });
          if (data.res == 0) {
            createMessage.success('邮件更新成功');
          }
          handleRefresh();
          isShowAlert.value = false;
        } catch (error) {
          isShowAlert.value = false;
        }
      };

      const getEmailListEmailData = async () => {
        try {
          const res = await getEmailListEmail();
          emailList.value = res || [];
          emailList.value.forEach((item) => {
            item.label = item.email;
            item.value = item.id;
          });
        } catch (error) {}
      };

      const handleChangeEmail = () => {
        const emailRecord = emailList.value.find((item) => item.id == emailInfo.value.id);
        internalEmail.handleChangeEmail(emailRecord);
      };

      onMounted(() => {
        if (internalEmail.emailInfo.value.id) {
          getEmailFetchMailData();
          handleRefresh();
        } else {
          console.log('Email is not setuped');
        }
        getEmailListEmailData();
      });
      return {
        registerTable,
        handleDelete,
        handleSuccess,
        handleDeleteBatch,
        handleView,
        handleRead,
        handleRefresh,
        handleTransmit,
        loading,
        isShowAlert,
        handleChangeEmail,
        userInfo,
        emailInfo,
        emailList,
        title,
        handleMoveData,
        handleSelect,
      };
    },
  });
</script>

<style lang="less" scoped>
  :deep(.ant-card-head-title) {
    padding: 8px 8px 0;
  }
  .custom-table {
    padding: 0;
    :deep(.ant-table-wrapper) {
      padding: 0;
    }
  }
  :deep(.ant-form) {
    padding: 10px 0 5px;
    margin-bottom: 0;
  }
</style>
